package cn.com.yto56.cainiao.exponent.es.controller;

import cn.com.yto56.cainiao.exponent.dto.AjaxResponse;
import cn.com.yto56.cainiao.exponent.dto.ExponentResponse;
import cn.com.yto56.cainiao.exponent.elasticsearch.service.QueryE2Service;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
public class HomeController {

    private static final String FMT = "yyyy-MM-dd";
    private static final int MAX_DAYS = 15;

    @Autowired
    private QueryE2Service queryE2Service;

    @GetMapping(value = {"", "/", "/index"})
    public ModelAndView index() {
        ModelAndView m = new ModelAndView("index");
        m.addObject("days", queryE2Service.getDays(MAX_DAYS, FMT));
        return m;
    }

    @PostMapping(value = "query")
    public AjaxResponse query(@RequestParam(value = "pullDate", defaultValue = "") String pd) {
        if (pd.length() == 0) {
            return new AjaxResponse().failure("查询时间不能为空");
        }
        try {
            Date pullDate = new SimpleDateFormat(FMT).parse(pd);
            List<ExponentResponse> data = new ArrayList<>();
            data.add(queryE2Service.queryLineAging(pullDate));
            data.add(queryE2Service.queryTimelyCanvass(pullDate));
            data.add(queryE2Service.queryPerfection(pullDate));
            data.add(queryE2Service.queryAccuracy(pullDate));
            return new AjaxResponse().success(data.stream().collect(Collectors.toMap(ExponentResponse::getType, e -> e)));
        } catch (ParseException e) {
            log.error("查询失败", e);
            return new AjaxResponse().failure("查询失败");
        }
    }

}
